<?php

namespace api\modules\v1\controllers;

use api\controllers\OnAuthController;
use api\modules\v1\forms\LoginForm;
use common\models\api\AccessToken;
use common\helpers\CommonHelper;
use services\api\AccessTokenService;
use services\member\MemberService;
use Yii;

/**
 * 登录接口
 *
 * Class SiteController
 * @package api\modules\v1\controllers
 */
class SiteController extends OnAuthController
{
    public $modelClass = '';

    /**
     * 不用进行登录验证的方法
     *
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['login'];

    /**
     * @api {post} /v1/site/login 登陆
     * @apiName login
     * @apiGroup Site
     *
     * @apiBody  {String} username          用户名
     * @apiBody  {String} password          密码
     *
     * @apiSuccess {Object}  data           返回数据
     */
    public function actionLogin()
    {
//        var_dump(Yii::$app->security->generatePasswordHash(Member::DEFAULT_PASSWORD));
//        var_dump(Yii::$app->security->generateRandomString());
//        exit();
        $params = Yii::$app->request->post();
        $params['group'] = AccessToken::GROUP_PC;
        $model = new LoginForm();
        $model->attributes = $params;
        if (!$model->validate()) {
            return CommonHelper::api(422, $this->getError($model));
        }

        // 记录登录信息
        $service = new AccessTokenService();
        return $service->login($model);
    }

    /**
     * @api {post} /v1/site/logout 登出
     * @apiName logout
     * @apiGroup Site
     * @apiUse CommonParam
     *
     * @apiSuccess {Object}  data           返回数据
     */
    public function actionLogout()
    {
        $service = new AccessTokenService();
        return $service->logout();
    }


    /**
     * @api {get} /v1/site/permissions    获取用户权限信息
     * @apiName permissions
     * @apiGroup Site
     * @apiUse CommonParam
     *
     * @apiSuccess {Array}  auth                    权限列表
     * @apiSuccess {Array}  auth.sider              菜单列表
     * @apiSuccess {Array}  auth.action             动作列表
     *
     */
    public function actionPermissions()
    {
        $memberService = new MemberService();
        return $memberService->getMemberPerssions();
    }
}
